<?php
require_once('SPARQL_Array.class.php');
/**
 * SPARQL_XML
 *
 * @package converters
 * @author Keith Alexander
 **/
class SPARQL_XML extends ConvertableObject
{
	/**
	 * to_boolean
	 * @param string $xml
	 * @return string 'TRUE' | 'false'
	 * @author Keith Alexander
	 **/
	public function to_boolean($xml)
	{
		$doc = new DomDocument();
		$doc->loadXML($xml);
		$boolean = $doc->getElementsByTagName('boolean')->item(0);
		return (strtolower($boolean->textContent)=='true')? 'true' : 'false';
	}
	
	
	/**
	 * to_array
	 *
	 * @return array
	 * @author Keith Alexander
	 **/
	public function to_array($value=false)
	{
		if(!$value) $value = $this->value();
		
		$sparql_array = array(
				'head'=> array(
					),
			
			); //this is the array we are creating
		
		$doc = new DOMDocument();
		$doc->loadXML(trim($value));
		$xpath = new DOMXPath($doc);
		$xpath->registerNamespace('s', 'http://www.w3.org/2005/sparql-results#');
				
		$variables = $xpath->query('//s:head/s:variable');
		foreach($variables as $var) $sparql_array['head']['vars'][]=$var->getAttribute('name');

		$links = $xpath->query('//s:head/s:link');
		foreach($links as $link) $sparql_array['head']['links'][]=$var->getAttribute('href');

		@$boolean = $xpath->query('//s:boolean')->item(0)->textContent;
		
		if(!empty($boolean))
		{
			$sparql_array['boolean'] = (strtolower($boolean)=='true');
		}
		else
		{
			$results = $xpath->query('//s:result');
			foreach($results as $result)
			{
				$bindings = $xpath->query('s:binding', $result);
				$row = array();				
				
				foreach($bindings as $binding)
				{
					$name = $binding->getAttribute('name');
					$child = $xpath->query('s:uri|s:literal|s:bnode', $binding)->item(0);
					$binding_arr = array(
						'type' => $child->localName,
						'value' => $child->textContent,
						);
					if($child->hasAttribute('datatype')) $binding_arr['datatype'] = $child->getAttribute('datatype');
					elseif($child->hasAttribute('xml:lang')) $binding_arr['lang'] = $child->getAttribute('xml:lang');
					
					$row[$name] = $binding_arr;	
				}
				$sparql_array['results']['bindings'][]= $row;

			}
		}
		
		return new SPARQL_Array($sparql_array);
	}
	
	
	
}

?>